import { addUrls } from '@/api/yyj/gbs/url'
import { addFiles } from '@/api/yyj/gbs/file'

const state = {
  goodFiles: [],
  goodImgs: [],
  goodCode: null
}

/**
 * 同步方法
 */
const mutations = {
  /**
   * 清空数据
   */
  CLEAR_GOOD_INFO: (state) => {
    state.goodFiles = []
    state.goodImgs = []
    state.goodCode = null
  },
  /**
   * 设置
   */
  SET_GOOD_FILES: (state, goodFiles) => {
    state.goodFiles = goodFiles
  },
  SET_GOOD_IMGS: (state, goodImgs) => {
    state.goodImgs = goodImgs
  },
  SET_GOOD_CODE: (state, goodCode) => {
    state.goodCode = goodCode
  }
}

/**
 * 异步方法
 */
const actions = {
  /**
   * 设置
   */
  setGoodFiles({ commit }, goodFiles) {
    commit('SET_GOOD_FILES', goodFiles)
  },
  setGoodImgs({ commit }, goodImgs) {
    commit('SET_GOOD_IMGS', goodImgs)
  },
  setGoodCode({ commit }, goodCode) {
    commit('SET_GOOD_CODE', goodCode)
  },

  /**
   * 提交文件和图片
   */
  submitData({ commit }) {
    const goodImgs = state.goodImgs.map(e => {
      return {
        urlPdCode: state.goodCode,
        urlName: e.name || e.url,
        urlPath: e.url
      }
    })
    const goodFiles = state.goodFiles.map(e => {
      return {
        filePdCode: state.goodCode,
        fileName: e.name || e.url,
        fileUrl: e.url,
        fileLength: e.length || ''
      }
    })
    return new Promise((resolve, reject) => {
      if (goodImgs.length > 0 && goodFiles.length > 0) {
        Promise.all([addUrls(goodImgs), addFiles(goodFiles)]).then(res => {
          console.log('promise Img FIle res ', res)
          // 清空数据
          commit('CLEAR_GOOD_INFO')
          resolve()
        }).catch(err => {
          reject(err)
        })
      } else if (goodImgs.length > 0) {
        addUrls(goodImgs).then(res => {
          console.log('promise Img FIle res ', res)
          // 清空数据
          commit('CLEAR_GOOD_INFO')
          resolve()
        }).catch(err => {
          reject(err)
        })
      } else if (goodFiles.length > 0) {
        addFiles(goodFiles).then(res => {
          console.log('promise Img FIle res ', res)
          // 清空数据
          commit('CLEAR_GOOD_INFO')
          resolve()
        }).catch(err => {
          reject(err)
        })
      } else {
        resolve()
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
